package com.hsylient.kafka.controller;

import cn.hutool.core.thread.ThreadUtil;
import com.hsylient.kafka.service.ThreadPoolService;
import com.hsylient.kafka.service.WaitTaskFinishService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class ThreadController {

    @Resource
    private ThreadPoolService threadPoolService;
    @Resource
    private WaitTaskFinishService waitTaskFinishService;

    @GetMapping("/info")
    public String dealData() {
        CompletableFuture<String>[] futures = new CompletableFuture[10];

        for (int i = 0; i < 10; i++) {
            CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                ThreadUtil.safeSleep(3000);
                return Thread.currentThread().getName();
            });
            futures[i] = future;
        }

        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures);

        CompletableFuture<String> combinedFuture = allFutures.thenApply(v ->
                Arrays.stream(futures)
                        .map(CompletableFuture::join)
                        .collect(Collectors.joining(", "))
        );

        return combinedFuture.join();
    }



    @GetMapping("/v1/thread/fixed/thread/pool")
    public void fixedThreadPool() {
        threadPoolService.fixedThreadPool();
    }


    @GetMapping("/v1/thread/method/parallel/stream")
    public void parallelStream() {
        waitTaskFinishService.methodByParallelStream();
    }
    @GetMapping("/v1/thread/method/completable/future")
    public void completableFuture() {
        waitTaskFinishService.methodCompletableFuture();
    }
    @GetMapping("/v1/thread/method/executor/completion")
    public void executorCompletion() {
        waitTaskFinishService.methodExecutorCompletion();
    }

}
